<?php

namespace app\admin\controller\games;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\Config as ConfigModel;
use app\common\model\Category;
use fast\Form;
/**
 * 游戏信息管理
 *
 * @icon fa fa-circle-o
 */
class GameInfo extends Backend
{
    
    /**
     * GameInfo模型对象
     * @var \app\admin\model\games\GameInfo
     */
    protected $model = null;
    protected $infoList = [];
    protected $noNeedRight = ['getsku','build_checkboxs','cxselect'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\games\GameInfo;
        $this->typemodel = new \app\admin\model\games\GameType();
        $this->attrmodel = new \app\admin\model\games\GameAttr();
        $this->gamemodel = new \app\admin\model\games\Game();
        // $list = \app\admin\model\games\Game::field('id,game')->select();
        // $typeList = \app\admin\model\games\GameType::field('id,title')->order('id asc')->select();
        
        
        // //游戏属性
        // $game_id = $this->request->get('game_id');
        // $attrlist = \app\admin\model\games\GameAttr::field('id,name')->select();
        // // $where = ['id','>',0];
        // if($game_id > 0){
        //     $con['game_id'] = $game_id;
        //     $attrlist = \app\admin\model\games\GameAttr::where($con)->field('id,name')->select();
        // }
        // $attrlist = array_column($attrlist,'name','id');
        // // dump($attrlist);
        // $this->view->assign([
        //     "list" => $list,
        //     "typeList" => $typeList,
        //     "attrlist" => $attrlist,
        // ]);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $infoList = $this->model::with('game,gametype,parent')->where($where)->order('game_id asc,id asc')->select();
            foreach ($infoList as $k => &$v) {
                $v['name'] = __($v['name']);
            }
            unset($v);
            Tree::instance()->init($infoList);
            $this->infoList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
            $pdata = [0 => __('None')];
            foreach ($this->infoList as $k => &$v) {
                $pdata[$v['id']] = $v['name'];
                unset($v['spacer']);
            }
            unset($v);
            $total = count($this->infoList);
            $result = array("total" => $total, "rows" => $this->infoList);

            return json($result);
        }
        return $this->view->fetch();
    }
    // public function index()
    // {
    //     //设置过滤方法
    //     $this->request->filter(['strip_tags', 'trim']);
    //     if ($this->request->isAjax()) {
    //         //如果发送的来源是Selectpage，则转发到Selectpage
    //         if ($this->request->request('keyField')) {
    //             return $this->selectpage();
    //         }
    //         list($where, $sort, $order, $offset, $limit) = $this->buildparams();

    //         $list = $this->model
    //             ->with('game,gametype,parent')
    //             ->where($where)
    //             ->order($sort, $order)
    //             ->paginate($limit);
            
    //         $result = array("total" => $list->total(), "rows" => $list->items());

    //         return json($result);
    //     }
    //     return $this->view->fetch();
    // }

    
    public function getsku()
    {
        //游戏属性
        $game_id = $this->request->post('game_id');
        $id = $this->request->post('id');
        $attrlist = $this->attrmodel::field('id,name')->select();
        // $where = ['id','>',0];
        if($game_id > 0){
            $where['game_id'] = $game_id;
            $attrlist = $this->attrmodel::where($where)->field('id,name')->select();
        }
        $attrlist = array_column($attrlist,'name','id');
        if($attrlist){
            $info =  $this->model->get($id);
            $html = $this->build_checkboxs('row[sku][]',$attrlist,$info['sku']);
            return json(['code' => 1, 'msg' => '', 'url' => '', 'data' => $html]);
        }else{
            $html = '<div class="checkbox"><input name="row[sku]" type="hidden"></div>';
            return json(['code' => 1, 'msg' => '', 'url' => '', 'data' => $html]);
        }
    }

    public function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }

    /**
     * 联动搜索
     */
    public function cxselect()
    {
        $type = $this->request->get('type');
        $game_id = $this->request->get('game_id');
        $gt_id = $this->request->get('gt_id');
        $list = null;
        $gametype = $this->gamemodel::where('id','=',$game_id)->column('type');
        // dump($gametype);
        if ($game_id !== '') {
            if ($type == 'game') {
                $list = $this->gamemodel::field('id as value,game as name')->select();
            } else if($type == 'gt_id') {
                $list = $this->typemodel->where('type','like','%'.$gametype[0].'%')->field('id as value,title as name')->order('id asc')->select();
            } else if($type == 'pid'){
                $gt_id = $gt_id - 1;
                $list = $this->model::where(['game_id'=>$game_id,'gt_id'=>$gt_id])->field('id as value,name,pid')->select();
                if(!$list){
                    $list[0]['value'] = 0;
                    $list[0]['name'] = '顶级分类';
                }else{
                    foreach($list as $k => &$v){
                        $pname = $this->model::where('id','=',$v['pid'])->column('name');
                        if($pname){
                            $v['name'] = $pname[0].'--'.$v['name'];
                        }
                        
                        unset($v['pid']);
                    }
                }
            }else{
                $list = $this->attrmodel::field('id as value,name')->select();
                // $list = array_column($list,'name','id');
            }
        }
        $this->success('', null, $list);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            if ($params) {
                try {
                    if($params['sku']){
                        $params['sku'] = implode(',',$params['sku']);
                        
                    }else{
                        $params['sku'] = '';
                    }
                    $result = $this->model->create($params);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    try {
                        ConfigModel::refreshFile();
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                    }
                    $this->success();
                } else {
                    $this->error($this->model->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['sku']){
                        $params['sku'] = implode(',',$params['sku']);
                        
                    }else{
                        $params['sku'] = '';
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
